//
//  TKYFileController.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/4.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYFileController.h"
#import "FileCell.h"
#import "TKYShowFileController.h"
#import "TKYChangeStationHouseController.h"
#import "UIViewController+CWLateralSlide.h"
#import "KXSearchBar.h"
#define KFileCellID @"FileCell"
#define kCell_Height 50
@interface TKYFileController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchBarDelegate>
@property (nonatomic, strong) BaseTabelView *tableV;
/**
 显示没有数据的view
 */
@property (nonatomic, strong)UIView *noDataView;

@property (nonatomic, strong) BaseTabelView *resultTableV;
@property (nonatomic, strong) NSMutableDictionary *results;


@property (nonatomic, strong)NSDictionary  *dataSource;
@property (nonatomic, strong)NSMutableArray  *sectionArray;
@property (nonatomic, strong)NSMutableArray  *stateArray;

@property(nonatomic,strong) UISearchController *searchControl;// 搜索条

@end

@implementation TKYFileController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置界面
    [self setUPUI];
    // 设置数据
    [self initDataSource];
    
    self.results = [NSMutableDictionary dictionary];
    
    [self setBarButtonItem];
    
    [self.view addSubview:self.tableV];
    [self.view addSubview:self.noDataView];
    self.noDataView.hidden = YES;
    
}

- (void)setBarButtonItem
{
    //隐藏导航栏上的返回按钮
    [self.navigationItem setHidesBackButton:YES];
    CGFloat searchBarHei;
    if (@available(iOS 11.0, *)) {
        searchBarHei = 55;
    }else {
        searchBarHei = 44;
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.searchControl=[[UISearchController alloc]initWithSearchResultsController:nil];
    [self.searchControl.searchBar sizeToFit];   //大小调整
    self.searchControl.hidesNavigationBarDuringPresentation = NO;
    self.searchControl.dimsBackgroundDuringPresentation = NO;
    self.searchControl.obscuresBackgroundDuringPresentation = NO;
    self.searchControl.searchBar.barTintColor = [UIColor whiteColor];
    
    UIOffset offset = {10.0,0};
    
    self.searchControl.searchBar.searchTextPositionAdjustment = offset;
    //拿到searchBar的输入框
    UITextField *searchTextField = [self.searchControl.searchBar valueForKey:@"_searchField"];
    //字体大小
    searchTextField.font = [UIFont systemFontOfSize:15];
    //输入框背景颜色
    searchTextField.backgroundColor = kRGBColor(248, 248, 248, 1);
    //设置搜索控制器的结果更新代理对象
    self.searchControl.searchResultsUpdater=self;
    self.searchControl.searchBar.delegate=self;
    self.searchControl.searchBar.frame = CGRectMake(0, MyNavBarHeight, kScreenWidth,searchBarHei);
    self.tableV.tableHeaderView = self.searchControl.searchBar;
    //解决：退出时搜索框依然存在的问题
    self.definesPresentationContext = YES;
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, self.searchControl.searchBar.kx_bottom-1, kScreenWidth, 1)];
    line.backgroundColor = kMainColour;
    [self.view addSubview:line];
}
#pragma mark-- 初始化数据
- (void)initDataSource
{
    self.sectionArray  = [NSMutableArray arrayWithObjects:@"施组方案",
                     @"施组图纸",
                     @"专项方案",
                     @"安全保障体系",
                     @"质量保障体系",nil];
    NSArray *one = @[@"文件1",@"文件1",@"文件1"];
    NSArray *two = @[@"文件2",@"文件2？",@"文件2"];
    NSArray *three = @[@"文件3",@"文件3",@"文件3"];
    NSArray *four = @[@"文件4",@"文件4",@"文件4",@"文件4"];
    
    //self.dataSource = [NSMutableArray arrayWithObjects:one,two,three,four, nil];
    // 最好是 这种列表是个字典   key 是页眉  里面value是数组 数组里面是各个cell
    self.dataSource = @{@"文件1":one,@"文件2":two,@"文件3":three};
    self.stateArray = [NSMutableArray array];
    
    for (int i = 0; i < self.dataSource.count; i++)
    {
        //所有的分区都是闭合
        [self.stateArray addObject:@"0"];
    }
}

#pragma mark--- 界面设计
/**
 设置界面
 */
- (void)setUPUI{
    self.navigationItem.title = @"文档";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav"] style:UIBarButtonItemStylePlain target:self action:@selector(changeStationHouseBarButtonItem:)];
    
    //导航右侧的消息按钮
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBarButton setImage:[UIImage imageNamed:@"message"] forState:UIControlStateNormal];
    rightBarButton.frame = CGRectMake(0, 0, 40, 40);
    [rightBarButton addTarget:self action:@selector(messageCerterAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarButton];
    // 1.2 右边
    [self.navigationItem.rightBarButtonItem pp_addBadgeWithText:nil];
    [self.navigationItem.rightBarButtonItem pp_moveBadgeWithX:0 Y:6];
    [self.navigationItem.rightBarButtonItem pp_setBadgeFlexMode:PPBadgeViewFlexModeHead];
    //隐藏消息按钮的小红点
    // [self.navigationItem.rightBarButtonItem pp_hiddenBadge ];
     [self.view addSubview:self.tableV];
}

#pragma mark - UISearchResultsUpdating
/**实现更新代理*/
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //获取到用户输入的数据
    NSString *searchText = searchController.searchBar.text;
        //清除搜索结果
    if (self.results != nil) {
        [self.results removeAllObjects];
    }
    // 先取出字典里所有的key放到数组
    NSArray *arr = [self.dataSource allKeys];
    
    for (int i = 0; i < arr.count; i++) {
        // 对应key取出value  是个数组
        NSArray *reArr = [self.dataSource objectForKey:arr[i]];
        // 需要创建一个新数组 保证每个value都会有个数组创建
        NSMutableArray *mm = [NSMutableArray array];
        for (NSString *person in reArr) {
            if ([person.lowercaseString rangeOfString:searchText.lowercaseString].location != NSNotFound) {
                [mm addObject:person];
            }
        }
        if (mm.count > 0) {
            [self.results setObject:mm forKey:arr[i]];
        }
    }
    
    NSLog(@"selectedGroupVc  %@",self.results);
    /**通知结果ViewController进行更新*/
    [self.tableV reloadData];
}


#pragma mark - UISearchBarDelegate
#pragma mark UISearchBarDelegate
// return NO to not become first responder
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
    return YES;
}

// called when text starts editing
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    [self.tableV reloadData];
}

// return NO to not resign first responder
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    return YES;
}

// called when text ends editing
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
}

// called before text changes
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    return YES;
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
}

// called when keyboard search button pressed 键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%s",__func__);
    NSLog(@"searchBar.text = %@",searchBar.text);
    if (!self.searchControl.active) {
        [self.tableV reloadData];
    }
    [self.searchControl.searchBar resignFirstResponder];
}

// called when bookmark button pressed
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
    [self.tableV reloadData];
}

// called when search results button pressed
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"%s",__func__);
}



//切换站点
- (void)changeStationHouseBarButtonItem:(UIBarButtonItem *)barButtonItem{
    TKYChangeStationHouseController *vc = [[TKYChangeStationHouseController alloc] init];
    vc.drawerType = DrawerTypeMaskLeft;
    // [self cw_pushViewController:vc drewerHiddenDuration:0.01];
    [self cw_showDrawerViewController:vc animationType:CWDrawerAnimationTypeMask configuration:nil];
}

- (void)messageCerterAction:(UIBarButtonItem *)barButtonItem{
    
    
}

#pragma mark --- UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.results.count > 0 )  {
        return self.results.count;
    }else {
        return self.dataSource.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.stateArray[section] isEqualToString:@"1"]){
        //如果是展开状态
        if (self.results.count > 0 )  {
            NSArray *a = [self.results allKeys];
            return [[self.results objectForKey:a[section]] count];
        }else {
            NSArray *a = [self.dataSource allKeys];
            return [[self.dataSource objectForKey:a[section]] count];
        }
    }else{
        //如果是闭合，返回0
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FileCell *cell = [tableView dequeueReusableCellWithIdentifier:KFileCellID];
    cell.selectedButton.hidden = YES;
    cell.fileName.textAlignment = NSTextAlignmentLeft;
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    cell.contentView.backgroundColor = [UIColor whiteColor];
    if (self.results.count > 0)  {
        NSArray *a = [self.results allKeys];
        cell.fileName.text = [self.results objectForKey:a[indexPath.section]][indexPath.row];
    }else {
        NSArray *a = [self.dataSource allKeys];
        cell.fileName.text = [self.dataSource objectForKey:a[indexPath.section]][indexPath.row];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.resultTableV) {
        return nil;
    }
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    [button setTag:section+1];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 60)];
    [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, button.kx_height-1, button.kx_width, 1)];
    line.backgroundColor = kMainColour;
    [button addSubview:line];
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, (kCell_Height-25)/2, 25, 25)];
    [imgView setImage:[UIImage imageNamed:@"folder"]];
    [button addSubview:imgView];
    
    UIImageView *_imgView = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth-30, (kCell_Height-6)/2, 10, 6)];
    
    if ([self.stateArray[section] isEqualToString:@"0"]) {
        _imgView.image = [UIImage imageNamed:@"ico_listdown"];
    }else if ([self.stateArray[section] isEqualToString:@"1"]) {
        _imgView.image = [UIImage imageNamed:@"ico_listup"];
    }
    [button addSubview:_imgView];
    
    UILabel *tlabel = [[UILabel alloc]initWithFrame:CGRectMake(45, (kCell_Height-20)/2, 200, 20)];
    [tlabel setBackgroundColor:[UIColor clearColor]];
    [tlabel setFont:[UIFont systemFontOfSize:14]];
    tlabel.textColor = kUIColorFromRGB(333333, 1);
    if (self.results.count > 0) {
        NSArray *a = [self.results allKeys];
        [tlabel setText:a[section]];
    }else {
        NSArray *a = [self.dataSource allKeys];
        [tlabel setText:a[section]];
    }
    [button addSubview:tlabel];
    return button;
}

#pragma mark  -select cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"iOS架构的认识过程" ofType:@"pdf"];
    if (filePath.length == 0) {
         KShowAlertWithMsg_ios8(@"此文件不存在");
        return;
    }
    NSURL *url = [NSURL fileURLWithPath:filePath];
    TKYShowFileController *webView = [[TKYShowFileController alloc]init];
    webView.url = url;
    [self.navigationController pushViewController:webView animated:YES];
}

/**
 页眉按钮点击
 */
- (void)buttonPress:(UIButton *)sender//headButton点击
{
    //判断状态值
    if ([self.stateArray[sender.tag - 1] isEqualToString:@"1"]){
        //修改
        [self.stateArray replaceObjectAtIndex:sender.tag - 1 withObject:@"0"];
    }else{
        [self.stateArray replaceObjectAtIndex:sender.tag - 1 withObject:@"1"];
    }
    [self.tableV reloadSections:[NSIndexSet indexSetWithIndex:sender.tag-1] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCell_Height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == self.resultTableV) {
        return 0.0001;
    }else{
        return 50;
    }
}

#pragma mark -- 懒加载
- (BaseTabelView *)tableV{
    if (_tableV == nil) {
        _tableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, SCREEN_WIDTH, kScreenHeight)style:UITableViewStyleGrouped];
        _tableV.delegate = self;
        _tableV.dataSource = self;
        [_tableV registerNib:[UINib nibWithNibName:@"FileCell" bundle:nil] forCellReuseIdentifier:KFileCellID];
    }
    return _tableV;
}

- (BaseTabelView *)resultTableV{
    if (_resultTableV == nil) {
        _resultTableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kScreenHeight)style:UITableViewStyleGrouped];
        _resultTableV.delegate = self;
        _resultTableV.dataSource = self;
        [_resultTableV registerNib:[UINib nibWithNibName:@"FileCell" bundle:nil] forCellReuseIdentifier:KFileCellID];
    }
    return _resultTableV;
}

/**
 提示没有数据view
 */
- (UIView *)noDataView
{
    if (!_noDataView) {
        // 添加一个"没有数据"的提醒
        _noDataView = [[UIView alloc]init];
        [self.view addSubview:_noDataView];
        UILabel *label = [[UILabel alloc]init];
        label.textColor  = [UIColor grayColor];
        label.text = @"没有搜索内容";
        [_noDataView addSubview:label];
        [label autoCenterInSuperview];
        [_noDataView autoCenterInSuperview];
    }
    return _noDataView;
}




@end
